前一天做過了基本型的recyclervivew,那今天除了原本製作recyclerView所需的流程與元件以外,我們需要另外加入兩個東西,分別是
ItemTouchHelperCallback 跟 ITHelperInterface
interface ITHelperInterface {
fun onItemMove(fromPosition:Int,toPosition:Int) //處理用上下拖曳來產生換位效果
fun onItemDissmiss(position:Int) //處理用左右滑動來刪除項目
}
class ItemTouchHelperCallback(var mAdapter: ITHelperInterface?): ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: ViewHolder): Int {
//設定可往上及往下拖曳
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
//設定可往左及往右滑動
val swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
//若不想要其中一個功能就改成ACTION_STATE_IDLE
//val dragFlags = ItemTouchHelper.ACTION_STATE_IDLE
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun isLongPressDragEnabled(): Boolean {
return true
}
//設定item可滑動
override fun isItemViewSwipeEnabled(): Boolean {
return true
}
//上下拖曳監聽事件
override fun onMove(
recyclerView: RecyclerView,
viewHolder: ViewHolder,
target: ViewHolder
): Boolean {
//呼叫ITHelperInterface的方法
mAdapter!!.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
return true
}
//左右滑動監聽事件
override fun onSwiped(viewHolder: ViewHolder, direction: Int) {
//呼叫ITHelperInterface的方法
mAdapter!!.onItemDissmiss(viewHolder.adapterPosition)
}
}
讓原先的Adapter繼承ITHelperInterface並且override裡面那兩個方法
class MyAdapter: RecyclerView.Adapter<BackpackAdapter.mViewHolder>(),ITHelperInterface {
//........
override fun onItemDissmiss(position: Int) {
unAssignList.removeAt(position)
notifyItemRemoved(position)
}
override fun onItemMove(fromPosition: Int, toPosition: Int) {
Collections.swap(unAssignList,fromPosition,toPosition)
notifyItemMoved(fromPosition,toPosition)
}
}
最後去Activity進行綁定啦
class MainActivity : AppCompatActivity() {
val mAdapter = MyAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_backpack)
//這裡的recyclerview指的是你在activity_main.xml裡的recyclerview
recyclerview.layoutManager = LinearLayoutManager(this)
recyclerview.adapter = backpackAdapter
val callback = ItemTouchHelperCallback(backpackAdapter)
val touchHelper = ItemTouchHelper(callback)
touchHelper.attachToRecyclerView(recyclerview)
}
}
Done!